package com.csust.travel.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csust.travel.Constants.ResultCode;
import com.csust.travel.entity.User;
import com.csust.travel.exception.ServiceException;
import com.csust.travel.mapper.UserMapper;
import com.csust.travel.model.DTO.UserLoginDto;
import com.csust.travel.model.R;
import com.csust.travel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public SaTokenInfo login(UserLoginDto request) {
        String userCode = request.getCode();
        String phone = request.getPhone();
        String redis_code = redisTemplate.opsForValue().get("check:code:" + phone);
        if(StrUtil.isEmpty(redis_code) ) throw new ServiceException(ResultCode.Fail, "验证码错误");
        if ( !redis_code.equals(userCode)) throw new ServiceException(ResultCode.Fail, "验证码错误");
        //1.查询用户是否存在
        User user = lambdaQuery().eq(User::getPhone, request.getPhone()).one();
        //2.不存在 自动创建用户
        if (null == user) {
            user = new User();
            String numbers = RandomUtil.randomNumbers(9);
            user.setNumber(numbers);
            user.setPhone(Long.valueOf(request.getPhone()));
            user.setProvince(request.getProvince());
            user.setCity(request.getCity());
            user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            user.setNickName("用户"+ numbers);
            user.setCreateTime(new Date().getTime());
            user.setUpdateTime(new Date().getTime());
            user.setStatus(9);
            boolean save = save(user);
            if (!save) throw new ServiceException(ResultCode.Fail);
        }else{
            if (user.getStatus() == 0) {
                throw new ServiceException(ResultCode.Fail,"账户被禁用");
            }
            user.setProvince(request.getProvince());
            user.setCity(request.getCity());
            user.setUpdateTime(new Date().getTime());
            boolean update = updateById(user);
            if (!update) throw new ServiceException(ResultCode.Fail);
        }
        StpUtil.login(user.getId());
        redisTemplate.delete("check:code:" + request.getPhone());
        //返回token
        return StpUtil.getTokenInfo();
    }


    @Override
    public SaTokenInfo loginPwd(UserLoginDto request) {
        User user = lambdaQuery().eq(User::getPhone, request.getPhone()).one();
        if(BeanUtil.isEmpty(user))throw new ServiceException(ResultCode.NotFindError,"第一次登陆，请选择手机号登录");
        String md5 = SaSecureUtil.md5(request.getPassword());
        if(!request.getPassword().equals(user.getPassword())) throw new ServiceException(ResultCode.Fail, "手机号或密码错误");
        user.setProvince(request.getProvince());
        user.setCity(request.getCity());
        user.setUpdateTime(new Date().getTime());
        boolean update = updateById(user);
        if (!update) throw new ServiceException(ResultCode.Fail);
        StpUtil.login(user.getId());
        return StpUtil.getTokenInfo();
    }



    @Override
    public R<User> getUserInfo() {
        Object loginId = StpUtil.getLoginId();
        User user = lambdaQuery().eq(User::getId, loginId).one();
        if (user == null) {
            throw new ServiceException(ResultCode.NotFindError, "用户不存在");
        }
        return R.ok(user);
    }

    @Override
    public void getLoginCode(String phone) {
        redisTemplate.opsForValue().set("check:code:" + phone, "123456", 120, TimeUnit.SECONDS);
    }
    @Override
    public R<User> getUserInfo(String userId) {
        User user = lambdaQuery().eq(User::getId, userId).one();
        if (user == null) {
            throw new ServiceException(ResultCode.NotFindError, "用户不存在");
        }
        return R.ok(user);
    }


}
